package org.whatever.aha.zjut.platform.controller.school;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.whatever.aha.zjut.base.constant.AuthConst;
import org.whatever.aha.zjut.base.constant.ErrorCode;
import org.whatever.aha.zjut.base.constant.RegexPattern;
import org.whatever.aha.zjut.base.dto.AjaxResult;
import org.whatever.aha.zjut.base.exception.AppException;
import org.whatever.aha.zjut.platform.dto.AcademyRegisterInfo;
import org.whatever.aha.zjut.platform.service.UserService;
import org.whatever.aha.zjut.platform.util.CheckUtil;
import org.whatever.aha.zjut.platform.vo.AcademyInfoVo;
import org.whatever.aha.zjut.platform.vo.project.ProjectStuRoughVo;

import javax.validation.constraints.Pattern;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Vc
 * @version 1.0
 * @Desc 创建、删除院级管理员账号
 * @date 2021/11/03 21:11
 */
@Api(tags = "校级管理员创建、删除院级管理员账号操作类")
@RequestMapping("/v1/school/operateAcademyAccount")
@RequiredArgsConstructor
@RestController
@Validated
@SaCheckRole(value = {AuthConst.R_supper, AuthConst.R_school}, mode = SaMode.OR)
public class AcademyAccountController {
    final UserService userService;

    /**
     * 创建学院管理员账号
     *
     * @param academyRegisterInfo
     * @return
     */
    @PostMapping("/createAcademy")
    public AjaxResult<Integer> createAcademy(@RequestBody AcademyRegisterInfo academyRegisterInfo) {
        //重复创建评委检查，手机号是否重复,用户名是否重复
        if(!StringUtils.isEmpty(academyRegisterInfo.getPhoneNumber()) && userService.getAllPhones().contains(academyRegisterInfo.getPhoneNumber())){
            throw new AppException(ErrorCode.PHONE_NUMBER_USED);
        }
        if(!StringUtils.isEmpty(academyRegisterInfo.getUsername()) && userService.getAllJudgeNames().contains(academyRegisterInfo.getUsername())){
            throw new AppException(ErrorCode.USERNAME_USED);
        }

        return AjaxResult.SUCCESS(userService.createAcademy(academyRegisterInfo));
    }

    /**
     * 删除学院管理员账号
     *
     * @param userId
     * @return
     */
    @DeleteMapping("/deleteAcademy/{userId}")
    public AjaxResult<Integer> deleteAcademy(@PathVariable("userId") int userId) {
        return AjaxResult.SUCCESS(userService.deleteAcademy(userId));
    }

    /**
     * 分页获取学院管理员账号
     *
     * @param pageNum
     * @param pageSize
     * @param academyListString
     * @return
     */
    @GetMapping("/getAcademyAccount")
    public AjaxResult<Map> getAcademyAccountPageable(
            @RequestParam(value = "pageNum", required = true, defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", required = true, defaultValue = "10") int pageSize,
            @RequestParam(value = "academyListString", required = false) String academyListString) {
        List<Integer> academyIdList = new ArrayList<>();
        if(academyListString != null && academyListString.length() > 0){
            String[] academyList = academyListString.split("-");
            for (int i = 0; i < academyList.length; i++) {
                academyIdList.add(Integer.parseInt(academyList[i]));
            }
        }
        return AjaxResult.SUCCESS(userService.getAcademyAccountPageable(academyIdList, (pageNum - 1) * pageSize, pageSize));
    }

    /**
     * 修改学院管理员账号信息（密码、停用等）
     *
     * @param userId
     * @param username
     * @param password
     * @param phoneNumber
     * @param academyId
     * @param disable
     * @param untie_time
     * @return
     */
    @PutMapping("/modifyAcademyAccount/{userId}")
    public AjaxResult<Integer> modifyAcademyAccount(@PathVariable("userId") int userId,
                                                    @RequestParam(value = "username", required = false) String username,
                                                    @RequestParam(value = "password", required = false)String password,
                                                    @Pattern(regexp = RegexPattern.PHONE_NUMBER)
                                                    @RequestParam(value = "phoneNumber", required = false)String phoneNumber,
                                                    @RequestParam(value = "academyId", required = false)Integer academyId,
                                                    @RequestParam(value = "disable", required = false)Boolean disable,
                                                    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
                                                    @JsonFormat(
                                                            pattern = "yyyy-MM-dd HH:mm:ss",
                                                            timezone = "GMT+8"
                                                    )
                                                    @RequestParam(value = "untie_time", required = false) Date untie_time) {
        //检测手机号、用户名使用
        if(!StringUtils.isEmpty(phoneNumber) && userService.getAllPhones().contains(phoneNumber)){
            throw new AppException(ErrorCode.PHONE_NUMBER_USED);
        }
        if(!StringUtils.isEmpty(username) && userService.getAllJudgeNames().contains(username)){
            throw new AppException(ErrorCode.USERNAME_USED);
        }
        return AjaxResult.SUCCESS(userService.modifyAcademyAccount(userId, username, password, phoneNumber, academyId, disable, untie_time));
    }

}
